package cn.ximart.passport.controller;

import cn.ximart.passport.pojo.dto.AdminAddNewDTO;
import cn.ximart.passport.pojo.dto.AdminLoginDTO;
import cn.ximart.passport.pojo.vo.AdminListItemVO;
import cn.ximart.passport.security.LoginPrincipal;
import cn.ximart.passport.service.IAdminService;
import cn.ximart.passport.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Api(tags = "管理员管理")
@RestController
@RequestMapping("/admins")
@CrossOrigin
public class AdminController {

    @Autowired
    private IAdminService adminService;

    @ApiOperation("添加管理员")
    @ApiOperationSupport(order = 100)
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    @PostMapping("/add-new")
    public JsonResult addNew(@RequestBody AdminAddNewDTO adminAddNewDTO) {
        log.debug("接收到的请求数据为:{}", adminAddNewDTO);
        adminService.addNew(adminAddNewDTO);
        return JsonResult.ok();
    }


    @ApiOperation("管理员登录")
    @ApiOperationSupport(order = 400)
    @PostMapping("/login")
    public JsonResult login(@RequestBody AdminLoginDTO adminLoginDTO) {
        log.debug("即将进行登录操作，接受的数据为：{}", adminLoginDTO);
        String jwt = adminService.login(adminLoginDTO);
        return JsonResult.ok(jwt);
    }


    @ApiOperation("管理员列表")
    @ApiOperationSupport(order = 401)
    @PreAuthorize("hasAuthority('/ams/admin/read')")
    @GetMapping("")
    public JsonResult list(@AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("接收到查询用户列表的请求");
        log.debug("当前认证信息中的当事人信息：{}",loginPrincipal);
        Long id = loginPrincipal.getId();
        log.debug("从认证信息中获取当前登录的管理员的id:{}",id);
        String username = loginPrincipal.getUsername();
        log.debug("从认证信息中获取当前登录的管理员的username:{}",username);
        List<AdminListItemVO> admins = adminService.list();
        return JsonResult.ok(admins);

    }


}
